import { defineStore } from 'pinia'
import {getMenus,getRoutes,getPerms} from '@/api/loginApi'
import router from '@/router'
import { dropdownMenuProps } from 'element-plus'

function generateNameMap(menus) {
    const nameMap = {}
    menus.forEach(menu => {
        handleMenu(menu,nameMap,[])
    })
    return nameMap
}

function handleMenu(menu,nameMap,titleArr) {
    titleArr.push(menu.title)
    nameMap[menu.name] = JSON.parse(JSON.stringify(titleArr))
    if(menu.children && menu.children.length > 0) {
        menu.children.forEach(menu => {
            let newTitleArr = JSON.parse(JSON.stringify(titleArr))
            handleMenu(menu,nameMap,newTitleArr)
        })
    }
}
    
export default defineStore('menu', {
    state: ()=> {
        return {
            routesMenusLoaded: false, // 路由菜单是否已加载
            menus: [], // 菜单
            routes: [], // 路由,
            perms: [], // 权限
        }
    },
    getters: {

    },
    actions: {
       loadRoutesMenus() {
        return new Promise(async (resolve,reject)=>{
            try {
                let menus = await getMenus()
                let routes = await getRoutes()
                let perms = await getPerms()

                // 保存路由
                this.routes = routes

                // 保存菜单
                this.menus = menus

                // 保存权限
                this.perms = perms

                // debugger
                const nameMap = generateNameMap(menus)

                //定义一个函数，引入所有views下.vue文件 
                const modules = import.meta.glob(`@/views/**/*.vue`);
                console.log(modules,'modules');
                /* 
                /src/views/404/NotFound.vue: () => import("/src/views/404/NotFound.vue")
                /src/views/Home.vue: () => import("/src/views/Home.vue")
                /src/views/login/index.vue: () => import("/src/views/login/index.vue?t=1679996129333")
                /src/views/sys/Menu.vue: () => import("/src/views/sys/Menu.vue")
                /src/views/sys/Role.vue: () => import("/src/views/sys/Role.vue")
                /src/views/sys/User.vue: () => import("/src/views/sys/User.vue")
                /src/views/test/test_1.vue: () => import("/src/views/test/test_1.vue")
                modules
                */
                
                // 动态加载路由
                routes.forEach(route=>{
                    // debugger
                    console.log(route.component);
                    console.log(route.component, modules[route.component]);
                    router.addRoute(
                        'layout', 
                        {
                            path: route.path,
                            name: route.name,
                            meta: {
                                titleArr: nameMap[route.name],
                                title: nameMap[route.name][nameMap[route.name].length-1]
                            },
                            // 好像直接以@开头,会报错，所以这干脆替换成相对路径吧
                            // component: ()=>import(/* @vite-ignore */route.component.replace('@',"../")) 
                            
                            // 改成使用import.meta.glob动态导入
                            component: modules[route.component]
                        }
                    )
                })

                router.addRoute({
                    path:'/:pathMatch(.*)*',
                    name: 'notFound',
                    component: ()=>import('../views/404/NotFound.vue')
                })
                

                console.log(router.getRoutes(),'加载路由 finished');
                this.routesMenusLoaded = true

                resolve()
            
            } catch (err) {
                reject(err)
            }

        })
       },

    }
})